package com.wsz.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wsz.common.Result;
import com.wsz.common.utils.MD5;
import com.wsz.system.pojo.User;
import com.wsz.system.service.UserService;
import com.wsz.vo.SysUserQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/admin/user")
public class SysUserController {

    @Autowired
    private UserService userService;

    @ApiOperation("添加用户")
    @PostMapping("addUser")
    public Result addUser(@RequestBody User user){
        user.setPassword(MD5.encrypt(user.getPassword()));
        user.setStatus(1);
        boolean save = userService.save(user);
        if(save) return Result.ok();
        else return Result.fail();
    }

    @ApiOperation("根据用户ID删除用户")
    @DeleteMapping("deleteById/{id}")
    public Result deleteById(@PathVariable String id){
        boolean b = userService.removeById(id);
        if(b) return Result.ok();
        else return  Result.fail();
    }

    @ApiOperation("根据用户ID修改用户信息")
    @PostMapping("updateById")
    public Result updateById(@RequestBody User user){
        user.setPassword(MD5.encrypt(user.getPassword()));
        boolean b = userService.updateById(user);
        if(b) return Result.ok();
        else return  Result.fail();
    }

    @ApiOperation("获取所有用户")
    @GetMapping("/getAllUser")
    public Result getAllUser() {
        List<User> list = userService.list();
        return Result.ok(list);
    }

    @ApiOperation("根据ID查询用户")
    @GetMapping("getUserById/{id}")
    public Result getUserById(@PathVariable String id){
        User byId = userService.getById(id);
        return Result.ok(byId);
    }

    @ApiOperation("条件分页查询用户列表")
    @PostMapping("/findPage/{page}/{limit}")
    public Result findPage(@PathVariable Long page,
                           @PathVariable Long limit,
                           @RequestBody(required = false) SysUserQueryVo sysUserQueryVo){
        Page<User> page1 = new Page<>(page,limit);
        IPage<User> page2 = userService.selectPage(page1,sysUserQueryVo);
        return Result.ok(page2);
    }

    @ApiOperation("更改用户状态")
    @PostMapping("/updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable String id,
                               @PathVariable Integer status){
        Boolean flag = userService.updateStatusById(id,status);
        if(flag) return Result.ok();
        else return Result.fail();
    }


}
